package com.api.gbhg.liuwenbo.version3.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.gbhg.liuwenbo.version3.pojo.IncomeBudgetExpend;
import com.customization.assets.util.DateTools;
import com.customization.commons.LogTool;
import org.docx4j.wml.P;
import weaver.conn.RecordSet;
import weaver.general.GCONST;

import javax.print.DocFlavor;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Description 收入预算支出统计-经费科报表
 * @Author  lwb
 * @Date 2023.2.9
 */
@Path("v3/IcomeBudgetExpend")
public class  IcomeBudgetExpendApi {
    private static LogTool logTool = new LogTool("/log/gbhg/report/IcomeBudgetExpendApi",false);
    private DateTools dateTools = new DateTools();

    public static void main(String[] args) {
        String rootPath = "D:\\WEAVER\\ecology\\";
        GCONST.setRootPath(rootPath);
        GCONST.setServerName("ecology");

        IcomeBudgetExpendApi api  = new IcomeBudgetExpendApi();
        Map params = new HashMap();
        params.put("nf","");
        params.put("ysly","");
        params.put("shrq","2023-10-01");
        System.err.println(api.getIcomeBudgetExpendList(params));
    }

    @POST
    @Path("/getIcomeBudgetExpendList")
    @Produces(MediaType.APPLICATION_JSON)
    public String getIcomeBudgetExpendList(Map param){
        Map msgMap = new HashMap();
        logTool.writeLog("接收参数："+param);
        //检查参数
        if (param == null ||!param.containsKey("nf")||!param.containsKey("ysly")  ){
            msgMap.put("code","400");
            msgMap.put("msg","缺少参数 请检查参数是否完整！");
            msgMap.put("data","");
            return JSON.toJSONString(msgMap);
        }
        //2023年4月11日 huangwm 增加预算来源查询条件
        try {
            String shrq = "";
            if(param.containsKey("shrq")){
                if(param.get("shrq").toString().isEmpty()){
                    shrq = dateTools.getCurrentDate();
                }else{
                    shrq = param.get("shrq").toString();
                }
            }
            if(!param.containsKey("shrq")){
                shrq = dateTools.getCurrentDate();
            }

            /**
             * 财政拨款收入数据
             * 需要显示每层结构 数据只取最末级
             */
            List<IncomeBudgetExpend> zyDataList = getZyLastleveData(param.get("nf").toString(),param.get("ysly").toString(),shrq);

            /**
             * 非财政拨款收入数据
             * 5和8的分类需要查询到项目层 其他则分类本身数据
             */
            List<IncomeBudgetExpend> fzyDataList = getFzyData(param.get("nf").toString(),param.get("ysly").toString(),shrq);

            Map map = new HashMap();
            map.put("中央财政拨款收入",zyDataList);
            map.put("非中央财政拨款收入",fzyDataList);

            msgMap.put("code",200);
            msgMap.put("msg","success");
            msgMap.put("data",map);
        } catch (Exception e) {
            msgMap.put("code","500");
            msgMap.put("msg",e.toString());
            msgMap.put("data","");
            return JSON.toJSONString(msgMap);
        }

        return JSON.toJSONString(msgMap);
    }

    public List<IncomeBudgetExpend> getFzyData(String nf,String ysly,String shrq){
        RecordSet rs = new RecordSet();
        String sql = "select sr.*,fl.mc from uf_fzysr sr left join uf_srysfl fl on sr.szfl = fl.id where sr.dw = 1 and sr.nf = year('"+shrq+"') ";
        rs.executeQuery(sql);
        List<IncomeBudgetExpend> list = new LinkedList<>();
        while (rs.next()){
            if (rs.getInt("szfl")==5||rs.getInt("szfl")==8){
                //5（其他收入）和8（项目收入）需要查询到项目
                List<IncomeBudgetExpend> fzysrData2 = getFzysrData2(nf, rs.getInt("szfl"), rs.getString("id"), rs.getString("mc"),ysly,shrq);
                list.addAll(fzysrData2);
            }else{
                //其他则本级查询即可
                if(ysly.isEmpty()){
                    List<IncomeBudgetExpend> dnData = getFzysrData1(nf, rs.getInt("szfl"), 1, 0, rs.getString("id"), rs.getString("mc")+"本年预算",shrq);
                    List<IncomeBudgetExpend> snData = getFzysrData1(nf, rs.getInt("szfl"), 1, 1, rs.getString("id"), rs.getString("mc")+"上年结转",shrq);
                    list.addAll(dnData);
                    list.addAll(snData);
                }else if(ysly.indexOf("当年")>=0){
                    List<IncomeBudgetExpend> dnData = getFzysrData1(nf, rs.getInt("szfl"), 1, 0, rs.getString("id"), rs.getString("mc")+"本年预算",shrq);
                    list.addAll(dnData);
                }else if(ysly.indexOf("上年")>=0){
                    List<IncomeBudgetExpend> snData = getFzysrData1(nf, rs.getInt("szfl"), 1, 1, rs.getString("id"), rs.getString("mc")+"上年结转",shrq);
                    list.addAll(snData);
                }

            }
        }
        return list;
    }

    /**
     * 无需查询项目
     * @param nf
     *          年份
     * @param fl
     *          分类id
     * @param zcqd
     *          支出渠道 0财政拨款 1非财政拨款
     * @param ysly
     *          预算来源 0当年预算 1上年预算
     * @param id
     *          id
     * @param name
     *          名称
     * @return
     */
    public List<IncomeBudgetExpend> getFzysrData1(String nf,int fl,int zcqd,int ysly,String id,String name,String shrq){
        RecordSet rs = new RecordSet();
        String sql = "select bmjjzcfl,zfjjzcfl,sum(uf_bxjl_kj_dt1.tybxje)as bxhj from uf_bxjl_kj_dt1 " +
                "left join uf_bxjl_kj on uf_bxjl_kj_dt1.lcid=uf_bxjl_kj.lcid where dw=1 and year(shrq)=year('"+shrq+"') and fzysrfl="+fl+" and zcqd = "+zcqd+" and ysly = "+ysly+" " +
                "AND shrq<='"+shrq+"'"+
                "group by bmjjzcfl,zfjjzcfl ";
        rs.executeQuery(sql);
        List<IncomeBudgetExpend> list = new LinkedList<>();
        while (rs.next()){
            IncomeBudgetExpend bean = new IncomeBudgetExpend();
            bean.setName(name);
            bean.setId(id);
            bean.setBmysjjfl(rs.getString("bmjjzcfl"));
            bean.setZfysjjfl(rs.getString("zfjjzcfl"));
            bean.setZcje(rs.getString("bxhj"));
            //bean.setYsje("0.00");
            //bean.setSyje(new BigDecimal(bean.getYsje()).subtract(new BigDecimal(bean.getZcje())).toString());
            list.add(bean);
        }
        return list;
    }

    /**
     * 需要查询项目
     * @param nf
     *          年份
     * @param fl
     *          分类id
     * @param id
     *          id
     * @param name
     *          名称
     */
    public List<IncomeBudgetExpend> getFzysrData2(String nf, int fl, String id, String name, String ysly,String shrq){
        RecordSet rs = new RecordSet();
        String sql = "select * from uf_fzysrxm where yssrfl ="+fl+" and szdw=1 and nf=year('"+shrq+"') ";
        rs.executeQuery(sql);
        List<IncomeBudgetExpend> list = new LinkedList<>();
        while (rs.next()){
            if(ysly.isEmpty()){
                IncomeBudgetExpend dnBean = new IncomeBudgetExpend();
                dnBean.setId(id);
                dnBean.setName(name+"本年预算");
                int i1 = setFzysrData2Je(nf, fl, 1, dnBean.getId(), 0, dnBean,shrq);
                if (i1>0)
                    list.add(dnBean);

                IncomeBudgetExpend snBean = new IncomeBudgetExpend();
                snBean.setId(id);
                snBean.setName(name+"上年结转");
                int i2 = setFzysrData2Je(nf, fl, 1, snBean.getId(), 1, snBean,shrq);
                if (i2>0)
                    list.add(snBean);
            } else if(ysly.indexOf("当年")>=0){
                IncomeBudgetExpend dnBean = new IncomeBudgetExpend();
                dnBean.setId(id);
                dnBean.setName(name+"本年预算");
                int i1 = setFzysrData2Je(nf, fl, 1, dnBean.getId(), 0, dnBean,shrq);
                if (i1>0)
                    list.add(dnBean);
            } else if(ysly.indexOf("上年")>=0){
                IncomeBudgetExpend snBean = new IncomeBudgetExpend();
                snBean.setId(id);
                snBean.setName(name+"上年结转");
                int i2 = setFzysrData2Je(nf, fl, 1, snBean.getId(), 1, snBean,shrq);
                if (i2>0)
                    list.add(snBean);
            }

        }
        return list;
    }

    /**
     * 获取非中央数据金额值
     * @param nf
     *          年份
     * @param fl
     *          分类id
     * @param zcqd
     *          支出渠道
     * @param xmid
     *          项目id
     * @param ysly
     *          预算来源
     * @param bean
     *          实体类
     */
    public int setFzysrData2Je(String nf,int fl,int zcqd,String xmid,int ysly,IncomeBudgetExpend bean,String shrq){
        RecordSet rs = new RecordSet();
        String sql = "select bmjjzcfl,zfjjzcfl,sum(uf_bxjl_kj_dt1.tybxje)as bxhj from uf_bxjl_kj_dt1 " +
                "left join uf_bxjl_kj on uf_bxjl_kj_dt1.lcid=uf_bxjl_kj.lcid where dw=1 and year(shrq)=year('"+shrq+"') and fzysrfl="+fl+
                " and zcdfczbkxm in("+xmid+") and zcqd = "+zcqd+" and ysly = "+ysly+" " +"AND shrq<='"+shrq+"'"+
                "group by bmjjzcfl,zfjjzcfl ";
        rs.executeQuery(sql);
        int count = 0;
        if(rs.next()){
            bean.setBmysjjfl(rs.getString("bmjjzcfl"));
            bean.setZfysjjfl(rs.getString("zfjjzcfl"));
            bean.setZcje(rs.getString("bxhj"));
            //bean.setYsje("0.00");
            //bean.setSyje(new BigDecimal(bean.getYsje()).subtract(new BigDecimal(bean.getZcje())).toString());
            count++;
        }
        return count;
    }

    /**
     * 获取中央末级数据
     * @param nf
     * @param ysly 上年or当年
     * @return
     */
    public List<IncomeBudgetExpend> getZyLastleveData(String nf,String ysly,String shrq) {
        RecordSet rs = new RecordSet();
        String sql = "select * from uf_zyczbksr_km where srnf = year('" +shrq+ "') and dw =1  ";
        rs.executeQuery(sql);
        List<IncomeBudgetExpend> list = new LinkedList<>();

        while (rs.next()) {
            if(ysly.isEmpty()){
                IncomeBudgetExpend dnbean = new IncomeBudgetExpend();
                dnbean.setCj(1);
                dnbean.setId(rs.getString("id"));
                String kmdm_dn = rs.getString("kmdm");
                dnbean.setName(kmdm_dn.substring(0,kmdm_dn.length()-rs.getString("gnkmmc").length())+"当年预算");
                //List<IncomeBudgetExpend> ejData = getEjData(rs.getString("id"), 0, 0);
                List<IncomeBudgetExpend> ejData_dn = getEjData(rs.getString("id"), "0",0,shrq);
                if (ejData_dn.size()<1||ejData_dn.isEmpty()){
                    //没有下级了+那么现数据已是最下级数据
                    List<IncomeBudgetExpend> dnJeData = setJeData(0, rs.getString("id"), "0", 0, 2, dnbean.getName()+"当年预算",shrq);
                    list.addAll(dnJeData);
                }else{
                    list.addAll(ejData_dn);
                }
                list.add(dnbean);


                IncomeBudgetExpend snbean = new IncomeBudgetExpend();
                snbean.setCj(1);
                snbean.setId(rs.getString("id"));
                String kmdm_sn = rs.getString("kmdm");
                snbean.setName(kmdm_sn.substring(0,kmdm_sn.length()-rs.getString("gnkmmc").length())+"上年结转");
                //List<IncomeBudgetExpend> ejData = getEjData(rs.getString("id"), 0, 0);
                List<IncomeBudgetExpend> ejData_sn = getEjData(rs.getString("id"),  "1",0,shrq);
                if (ejData_sn.size()<1||ejData_sn.isEmpty()){
                    //没有下级了+那么现数据已是最下级数据
                    List<IncomeBudgetExpend> snJeData = setJeData(0, rs.getString("id"),"1", 0, 2, snbean.getName()+"上年结转",shrq);
                    list.addAll(snJeData);
                }else{
                    list.addAll(ejData_sn);
                }
                list.add(snbean);
            }else{
                if(ysly.indexOf("当年")>=0){
                    IncomeBudgetExpend dnbean = new IncomeBudgetExpend();
                    dnbean.setCj(1);
                    dnbean.setId(rs.getString("id"));
                    String kmdm = rs.getString("kmdm");
                    dnbean.setName(kmdm.substring(0,kmdm.length()-rs.getString("gnkmmc").length())+"当年预算");
                    //List<IncomeBudgetExpend> ejData = getEjData(rs.getString("id"), 0, 0);
                    List<IncomeBudgetExpend> ejData = getEjData(rs.getString("id"), "0",0,shrq);
                    if (ejData.size()<1||ejData.isEmpty()){
                        //没有下级了+那么现数据已是最下级数据
                        List<IncomeBudgetExpend> dnJeData = setJeData(0, rs.getString("id"), "0", 0, 2, dnbean.getName()+"当年预算",shrq);
                        list.addAll(dnJeData);
                    }else{
                        list.addAll(ejData);
                    }
                    list.add(dnbean);
                }else{
                    IncomeBudgetExpend snbean = new IncomeBudgetExpend();
                    snbean.setCj(1);
                    snbean.setId(rs.getString("id"));
                    String kmdm = rs.getString("kmdm");
                    snbean.setName(kmdm.substring(0,kmdm.length()-rs.getString("gnkmmc").length())+"上年结转");
                    //List<IncomeBudgetExpend> ejData = getEjData(rs.getString("id"), 0, 0);
                    List<IncomeBudgetExpend> ejData_sn = getEjData(rs.getString("id"),  "1",0,shrq);
                    if (ejData_sn.size()<1||ejData_sn.isEmpty()){
                        //没有下级了+那么现数据已是最下级数据
                        List<IncomeBudgetExpend> snJeData = setJeData(0, rs.getString("id"),"1", 0, 2, snbean.getName()+"上年结转",shrq);
                        list.addAll(snJeData);
                    }else{
                        list.addAll(ejData_sn);
                    }
                    list.add(snbean);
                }
            }
        }
        return list;
    }


    /**
     *
     * @param kmid
     *          科目id
     * @param ysly
     *          预算来源
     * @param zcqd
     *          支出渠道
     * @return
     */
    public List<IncomeBudgetExpend> getEjData(String kmid,String ysly,int zcqd,String shrq){
        RecordSet rs = new RecordSet();
        String sql = "select * from uf_zyczbksr_xj where szgnkm = "+kmid+" and sjzxsr is null";
        rs.executeQuery(sql);
        List<IncomeBudgetExpend> list = new LinkedList<>();
        while (rs.next()){
            IncomeBudgetExpend bean = new IncomeBudgetExpend();
            bean.setCj(2);
            bean.setSjid(kmid);
            bean.setId(rs.getString("id"));
            bean.setName(rs.getString("srzx")+(ysly.equals("0")?"当年预算":"上年结转"));
            List<IncomeBudgetExpend> xjList = getXjData(rs.getString("id"),3,bean.getName(),ysly,zcqd,shrq);
            if (xjList.size()<1||xjList.isEmpty()){
                //没有下级了+那么现数据已是最下级数据
                List<IncomeBudgetExpend> jeList = setJeData(1, rs.getString("id"), ysly, zcqd, 3, bean.getName(),shrq);
                list.addAll(jeList);
            }else{
                list.addAll(xjList);
            }
            list.add(bean);
        }
        return list;
    }

    /**
     * 递归寻找最下级
     * @param sjid
     *          上级id
     * @param cj
     *          层级
     * @param name
     *          名称
     * @return
     */
    public List<IncomeBudgetExpend> getXjData(String sjid,int cj,String name,String ysly,int zcqd,String shrq){
        RecordSet rs = new RecordSet();
        String sql = "select * from uf_zyczbksr_xj where sjzxsr = "+sjid+" ";
        rs.executeQuery(sql);
        List<IncomeBudgetExpend> list = new LinkedList<>();
        while (rs.next()){
            //list.add
            IncomeBudgetExpend bean = new IncomeBudgetExpend();
            bean.setCj(cj);
            bean.setSjid(sjid);
            bean.setId(rs.getString("id"));
            List<IncomeBudgetExpend> resultList = getXjData(rs.getString("id"),(cj+1),name,ysly,zcqd,shrq);
            if (resultList.size()<1||resultList.isEmpty()){
                //没有下级了+那么现数据已是最下级数据
                List<IncomeBudgetExpend> jeList = setJeData(1, rs.getString("id"), ysly, zcqd, cj, name,shrq);
                list.addAll(jeList);
            }else{
                list.addAll(resultList);
            }
            list.add(bean);
        }
        return list;
    }


    /**
     * 获取金额数据
     * @param kmjxj
     *          科目级还是下级参数 0：科目，1：下级
     * @param id
     *          id
     * @param ysly
     *          预算来源;0当年预算1上年结转
     * @param zcqd
     *          支出渠道;0财政1非财政
     * @param cj
     *          层级
     * @param name
     *          名称
     */
    public List<IncomeBudgetExpend> setJeData(int kmjxj,String id,String ysly,int zcqd,int cj,String name,String shrq){

        RecordSet rs = new RecordSet();
        String sql = "select bmjjzcfl,zfjjzcfl,sum(d1.tybxje)as bxhj from uf_bxjl_kj_dt1 d1 left join uf_bxjl_kj m on d1.lcid=m.lcid  where kmjxj="+kmjxj+
                " and dygnkmbid="+id+" and ysly="+ysly+" and zcqd = "+zcqd+
                "and shrq<='"+shrq+"'"+
                " group by bmjjzcfl,zfjjzcfl";
        rs.executeQuery(sql);
        List<IncomeBudgetExpend> jeList = new LinkedList<>();
        while (rs.next()){
            IncomeBudgetExpend ib = new IncomeBudgetExpend();
            ib.setName(name);
            ib.setCj(cj);
            ib.setSjid(id);
            ib.setBmysjjfl(rs.getString("bmjjzcfl"));
            ib.setZfysjjfl(rs.getString("zfjjzcfl"));
            ib.setZcje(rs.getString("bxhj"));
            //ib.setYsje("0.00");
            //ib.setSyje(new BigDecimal(ib.getYsje()).subtract(new BigDecimal(ib.getZcje())).toString());
            jeList.add(ib);
        }
        return jeList;
    }
}
